package org.jeecg.chase.modules.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.jeecg.chase.modules.entity.AdhCouponInfo;
import org.jeecg.chase.modules.merch.entity.AdhMerchInfo;
import org.jeecg.chase.modules.merch.service.IAdhMerchInfoService;
import org.jeecg.chase.modules.service.IAdhCouponInfoService;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.modules.system.entity.SysPermission;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;

/**
 * @author leikai
 * @version 1.0
 * @description:
 * @date 2022/03/05/0005 19:54
 */
@Slf4j
@RestController
@RequestMapping("/adh/coupon")
public class AdhCouponInfoController {

    @Autowired
    private IAdhCouponInfoService adhCouponInfoService;

    @Autowired
    private IAdhMerchInfoService adhMerchInfoService;


    /**
     * 分页查询
     *
     * @param adhCouponInfo
     * @param pageNo
     * @param pageSize
     * @param req
     * @return org.jeecg.common.api.vo.Result<com.baomidou.mybatisplus.core.metadata.IPage < org.jeecg.chase.modules.entity.AdhCouponInfo>>
     * @author leikai
     * @date 2022/03/05/0005 20:01
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @AutoLog(value = "优惠券分页查询", operateType = 1)
    public Result<IPage<AdhCouponInfo>> queryPageList(AdhCouponInfo adhCouponInfo,
                                                      @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                      @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                      HttpServletRequest req) {
        Result<IPage<AdhCouponInfo>> result = new Result<IPage<AdhCouponInfo>>();
        String merchCategory = req.getParameter("merchCategory");
        QueryWrapper<AdhCouponInfo> queryWrapper = QueryGenerator.initQueryWrapper(adhCouponInfo, req.getParameterMap());
        if(StringUtils.isNotBlank(merchCategory)){
            queryWrapper.apply(" merch_id IN (SELECT id FROM `adh_merch_info` WHERE merch_category='"+merchCategory+"')");
        }
        Page<AdhCouponInfo> page = new Page<AdhCouponInfo>(pageNo, pageSize);
        IPage<AdhCouponInfo> pageList = adhCouponInfoService.page(page, queryWrapper);
        result.setSuccess(true);
        result.setResult(pageList);
        return result;
    }

    /**
     * 新增
     *
     * @param adhCouponInfo
     * @return org.jeecg.common.api.vo.Result<org.jeecg.chase.modules.entity.AdhCouponInfo>
     * @author leikai
     * @date 2022/03/05/0005 20:01
     */
    @PostMapping("/add")
    @AutoLog(value = "优惠券新增", operateType = 2)
    public Result<AdhCouponInfo> add(@RequestBody AdhCouponInfo adhCouponInfo) {
        Result<AdhCouponInfo> result = new Result<AdhCouponInfo>();
        try {
            adhCouponInfo.setCreateTime(new Date());
            adhCouponInfo.setCouponDiscount(new BigDecimal("1"));
            adhCouponInfo.setAdvancePurchasePrice(BigDecimal.ZERO);
            this.adhCouponInfoService.save(adhCouponInfo);
            result.success("添加成功");
        } catch (Exception e) {
            e.printStackTrace();
            result.error500("操作失败");
        }
        return result;
    }

    /**
     * 修改
     *
     * @param adhCouponInfo
     * @return org.jeecg.common.api.vo.Result<org.jeecg.chase.modules.entity.AdhCouponInfo>
     * @author leikai
     * @date 2022/03/05/0005 20:02
     */
    @PostMapping("/edit")
    @AutoLog(value = "优惠券修改", operateType = 3)
    public Result<AdhCouponInfo> edit(@RequestBody AdhCouponInfo adhCouponInfo) {
        Result<AdhCouponInfo> result = new Result<AdhCouponInfo>();
        AdhCouponInfo adhShopCategoryOld = this.adhCouponInfoService.getById(adhCouponInfo.getId());
        if (adhShopCategoryOld == null) {
            result.error500("未找到对应实体");
        } else {
            adhCouponInfo.setUpdateTime(new Date());
            boolean ok = this.adhCouponInfoService.updateById(adhCouponInfo);
            if (ok) {
                result.success("修改成功");
            }
        }
        return result;
    }

    /**
     * 删除
     *
     * @param id
     * @return org.jeecg.common.api.vo.Result<?>
     * @author leikai
     * @date 2022/03/05/0005 20:03
     */
    @GetMapping("/delete")
    @AutoLog(value = "优惠券删除", operateType = 4)
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        try {
            this.adhCouponInfoService.removeById(id);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("删除失败");
        }
        return Result.OK("删除成功");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return org.jeecg.common.api.vo.Result<org.jeecg.modules.system.entity.SysPermission>
     * @author leikai
     * @date 2022/03/05/0005 20:04
     */
    @RequestMapping(value = "/deleteBatch", method = RequestMethod.GET)
    @AutoLog(value = "优惠券批量删除", operateType = 4)
    public Result<SysPermission> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        Result<SysPermission> result = new Result<>();
        try {
            String[] arr = ids.split(",");
            List<String> idList = Arrays.asList(arr);
            adhCouponInfoService.removeByIds(idList);
            result.success("删除成功!");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500("删除成功!");
        }
        return result;
    }

    /**
     * 状态修改
     *
     * @param param
     * @return org.jeecg.common.api.vo.Result<?>
     * @author leikai
     * @date 2022/03/05/0005 20:05
     */
    @PostMapping("/updateStatus")
    @AutoLog(value = "优惠券状态修改", operateType = 3)
    public Result<?> updateStatus(@RequestBody Map<String, String> param) {
        String id = param.get("id");
        String status = param.get("status");
        if (StringUtils.isBlank(id) || StringUtils.isBlank(status)) {
            return Result.error("参数错误");
        }
        if (status.equals("2")) {
            boolean ok = this.adhCouponInfoService.updateStatus(id, 2);
            if (ok) {
                return Result.OK("发布成功");
            }
        } else if (status.equals("3")) {
            boolean ok = this.adhCouponInfoService.updateStatus(id, 3);
            if (ok) {
                return Result.OK("下架成功");
            }
        }
        return Result.OK("操作失败");
    }

    @GetMapping("/queryMerchList")
    @AutoLog(value = "优惠券状态修改", operateType = 1)
    public Result<List<Map<String, Object>>> queryMerchList() {
        Result<List<Map<String, Object>>> result = new Result<List<Map<String, Object>>>();
        try {
            LambdaQueryWrapper<AdhMerchInfo> query = new LambdaQueryWrapper<AdhMerchInfo>();
            List<AdhMerchInfo> list = this.adhMerchInfoService.list(query);
            ArrayList<Map<String, Object>> arrayList = new ArrayList<>();
            list.forEach(item -> {
                HashMap<String, Object> map = new HashMap<>();
                map.put("value", item.getId());
                map.put("text", item.getMerchName());
                arrayList.add(map);
            });
            result.setResult(arrayList);
            result.isSuccess();
        } catch (Exception e) {
            e.printStackTrace();
            result.error500("查询失败");
        }
        return result;
    }
}
